package com.zy.mc_module.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hwangjr.rxbus.RxBus;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zy.mc_module.R;
import com.zy.mc_module.mvp.base.IPresenter;
import com.zy.mc_module.mvp.base.IView;
import com.zy.mc_module.utils.AppTools;
import com.zy.mc_module.utils.FixMemLeak;
import com.zy.mc_module.utils.StringsUtils;
import com.zy.mc_module.utils.loadsir.EmptyCallback;
import com.zy.mc_module.utils.loadsir.ErrorCallback;
import com.zy.mc_module.utils.loadsir.LoadingCallback;

import java.util.List;

/**
 * Created on 18/10/20
 * Fragment基类
 */
public abstract class BaseFragment<V extends IView, P extends IPresenter<V>> extends Fragment implements View.OnTouchListener{
    public String TAG = getClass().getSimpleName() + "";
    protected P presenter;
    protected Context context;
    private Unbinder unbinder;
    //Fragment View
    private View convertView;
    private LoadService loadService;
    //是否使用LoadSir
    private boolean isNeedLoadSir = false;
    //指定需要加载的视图,-1代表未指定
    private int loadViewid = -1;

    //视图是否加载完毕
    private boolean isViewPrepare = false;
    //数据是否加载过了
    protected boolean hasLoadData = false;

    //下拉刷新
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;

    /**
     * 分页加载
     **/
    protected int page = 1;//页数
    protected int size = 10;//每页数目

    /***
     * 布局文件Id
     */
    protected abstract int getLayoutId();

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        if (null != getActivity())
            getActivity().overridePendingTransition(R.anim.activity_in_from_right, R.anim.activity_out_from_left);
    }

    /***
     * 绑定Activity
     */
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        presenter = createPresenter();
    }

    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        if (convertView == null) {
            convertView = inflater.inflate(getLayoutId(), container, false);
        }
        //是否使用RxBus
        if (isNeedRxBus()) {
            RxBus.get().register(this);
        }
        //判断LoadSir
        isLoadSir();
        //是否使用LoadSir
        if (isNeedLoadSir) {
            //判断 是否指定了需要加载的视图
            loadService = LoadSir.getDefault().register(
                    -1 == loadViewid ? convertView : convertView.findViewById(loadViewid)
                    , (Callback.OnReloadListener) v -> reloadData());

            // return loadService.getLoadLayout();
            // return convertView;
            return -1 == loadViewid ? loadService.getLoadLayout() : convertView;
        } else {
            return convertView;
        }
    }

    /***
     * onCreateView执行完毕后调用
     */
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setOnTouchListener(this);
        //Fragment绑定ButterKnife
        unbinder = ButterKnife.bind(this, convertView);
        if (null != presenter) {
            //绑定Activity
            presenter.attachView((V) this);
        }
        //初始化视图
        initView(savedInstanceState);
        // TODO: 18/12/17  可以将初始化事件放到 懒加载那里 应该可以避免 RecyclerView 的Adapter点击事件为空 
        //初始化事件
        initListener();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;//消费掉点击事件,防止跑到下一层去
    }

    /***
     * Fragment创建完
     */
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //视图加载完了
        isViewPrepare = true;
        //懒加载
        LazyLoadData();
    }

    /***
     * Fragment UI是否可见
     */
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //UI可见进行懒加载
            LazyLoadData();
        }
    }

    /***
     * 懒加载Fragment数据
     */
    private void LazyLoadData() {
        //临时添加的方法,数据加载过了的也可以再次加载
        if (getUserVisibleHint() && isViewPrepare) {
            LoadData();
        }
        //只有在Fragment UI可见，视图已经加载完，并且没有加载过数据才能进行懒加载
        if (getUserVisibleHint() && isViewPrepare && !hasLoadData) {
            //懒加载数据
            LazyLoad();
            hasLoadData = true;
        }
    }


    /***
     * 创建Mvp Presenter实例
     */
    protected P createPresenter() {
        return null;
    }

    protected void initView(Bundle savedInstanceState) {

    }

    protected void initListener() {

    }

    /***
     * 临时添加的方法,数据加载过了的也可以再次加载
     */
    protected void LoadData() {

    }

    /***
     * 懒加载数据
     */
    protected abstract void LazyLoad();

    /***
     * LoadSir的重新加载数据
     */
    protected void reloadData() {

    }

    /***
     * 是否使用RxBus
     */
    protected boolean isNeedRxBus() {
        return false;
    }

    /***
     * 是否使用LoadSir等一系列功能
     * arg[0]:使用LoadSir
     * arg[1]:指定需要加载的视图
     */
    protected void isLoadSir(Object... objects) {
        if (objects.length == 1) {
            //使用LoadSir,未指定加载视图
            isNeedLoadSir = (boolean) objects[0];
        } else if (objects.length == 2) {
            //使用LoadSir,并指定需要加载视图
            isNeedLoadSir = (boolean) objects[0];
            loadViewid = (int) objects[1];
        }
    }

    /***
     * 封装下拉刷新/上拉加载逻辑
     */
    protected void initRefresh(SmartRefreshLayout refreshLayout, RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
        this.refreshLayout = refreshLayout;

        //下拉刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.setEnableLoadMore(true);
                page = 1;
                refreshData(true);
            }
        });
        //上拉加载
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                page++;
                refreshData(false);
            }
        });
    }

    /***
     * 刷新加载数据
     */
    protected void refreshData(boolean ReOrLo) {
    }

    /***
     * 刷新完成
     */
    protected void refreshComplete(Object object) {
        if (object instanceof List) {
            List list = (List) object;
            Adapter recyclerViewAdapter = recyclerView.getAdapter();
            if (null != recyclerViewAdapter) {
                if (recyclerViewAdapter instanceof BaseAdapter) {
                    BaseAdapter adapter = (BaseAdapter) recyclerView.getAdapter();
                    if (page == 1) {
                        adapter.setAll(list);
                        recyclerView.scrollToPosition(0);
                    } else {
                        adapter.addAll(list);
                    }
                } else if (recyclerViewAdapter instanceof BaseQuickAdapter) {
                    BaseQuickAdapter adapter = (BaseQuickAdapter) recyclerView.getAdapter();
                    if (page == 1) {
                        adapter.setNewData(list);
                        recyclerView.scrollToPosition(0);
                    } else {
                        adapter.addData(list);
                    }
                }
            }
            if (StringsUtils.isEmpty(list) && page > 1) {
                page--;
                refreshLayout.setEnableLoadMore(false);
            }
        } else if (object instanceof Boolean) {
            boolean b = (boolean) object;
            if (b && page > 1) {
                page--;
            }
        }
        AppTools.finishRefresh(refreshLayout);
    }

    //--------------------------------LoadSir-----------------------------------

    /***
     * 显示加载页
     */
    public void showLoading() {
        if (null != loadService) {
            loadService.showCallback(LoadingCallback.class);
        }
    }

    /***
     * 关闭加载页
     */
    public void disLoading() {
        loadService.showSuccess();
    }

    /***
     * 请求错误页
     */
    public void showError() {
        loadService.showCallback(ErrorCallback.class);
    }

    public void showError(List list) {
        if (null == list || list.size() <= 0) {
            loadService.showCallback(ErrorCallback.class);
        } else {
            disLoading();
        }
    }

    /***
     * 暂无数据页
     */
    public void showEmpty() {
        loadService.showCallback(EmptyCallback.class);
    }

    /***
     * 暂无数据页
     */
    public void showEmpty(Class<? extends Callback> callback) {
        loadService.showCallback(callback);
    }

    public void showEmpty(List list) {
        if (null == list || list.size() <= 0) {
            loadService.showCallback(EmptyCallback.class);
        } else {
            disLoading();
        }
    }

    public void showEmpty(List list, Class<? extends Callback> callback) {
        if (null == list || list.size() <= 0) {
            loadService.showCallback(callback);
        } else {
            disLoading();
        }
    }

    public View LayoutInflater(int layoutId, ViewGroup view) {
        return LayoutInflater.from(context).inflate(layoutId, view, false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //解绑ButterKnife
        if (null != unbinder) {
            unbinder.unbind();
            unbinder = null;
        }
        if (isNeedRxBus()) {
            //注销RxBus
            RxBus.get().unregister(this);
        }
        if (null != presenter) {
            presenter.detachView();
            presenter = null;
        }
        //取消订阅
        //SubscriptionManager.getInstance().cancelall();
        FixMemLeak.fixLeak(context);
    }
}
